package br.fxfc.android.daysuntil;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import br.fxfc.android.daysuntil.DBHelper.TableDaysUntil;

public class Add extends Activity {
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	private static final String TAG = "Add";
	private static final int menuSave = 0x0001;
	private static final int menuCancel = 0x0002;
	private SQLiteDatabase dbReadWrite;
	private DBHelper db;
	private TextView editEventName;
	private DatePicker dateEvent;
	private TimePicker timeEvent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add);

		// Inicia banco de dados
		db = new DBHelper(this);
		dbReadWrite = db.getWritableDatabase();

		editEventName = (TextView) findViewById(R.id.editEventName);
		dateEvent = (DatePicker) findViewById(R.id.dateEvent);
		timeEvent = (TimePicker) findViewById(R.id.timeEvent);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, menuSave, 0, R.string.save);
		menu.add(0, menuCancel, 0, R.string.cancel);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		StringBuilder dataString = new StringBuilder()
		// Month is 0 based so add 1
				.append(dateEvent.getYear()).append("-").append(
						pad(dateEvent.getMonth() + 1)).append("-").append(
						pad(dateEvent.getDayOfMonth())).append(" ").append(
						pad(timeEvent.getCurrentHour())).append(":").append(
						pad(timeEvent.getCurrentMinute()));

		switch (item.getItemId()) {
		case menuSave:
			insertRow(editEventName.getText().toString(), dataString.toString(),
					false);
			finish();
			break;
		case menuCancel:
			finish();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void insertRow(String text, String date, Boolean passed) {

		String sql = "insert into " + DBHelper.TableDaysUntil.NAME
				+ " ("
				+ TableDaysUntil.COL_TEXT + ", "
				+ TableDaysUntil.COL_DATETIME + ", "
				+ TableDaysUntil.COL_PASSED
				+ ") values ('" + text + "','" + date + "',"
				+ Integer.parseInt(passed.toString()) + ")";
		Log.d(TAG, "insertRow(): sql = " + sql);
		dbReadWrite.execSQL(sql);
	}

	private static String pad(int c) {
		if (c >= 10) {
			return String.valueOf(c);
		} else {
			return "0" + String.valueOf(c);
		}
	}

}
